package top.loveyumin1314.music.lottery;


import top.loveyumin1314.music.bean.LotteryBean;
import top.loveyumin1314.music.bean.UserActionBean;
import top.loveyumin1314.music.cmd.CreateResponse;
import top.loveyumin1314.music.code.ActionCode;
import top.loveyumin1314.music.serviceimpl.BroadcastService;

import java.io.Console;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * author Kerry
 * date 2017/10/12
 * desp
 */

public class LotteryThread implements Runnable {

    public static final long NOTIFIY_TIME = 40L;
    private Random random = new Random();

    @Override
    public void run() {
        UserActionBean progress = new UserActionBean();
        progress.setActionCode(ActionCode.LOTTORY_PROGRESS);
        CreateResponse createResponse = CreateResponse.create();
        while (LotteryService.IS_START_LOTTERY.get()) {

            try {
                Thread.sleep(NOTIFIY_TIME);
            } catch (InterruptedException ignored) {
            }

            if (!BroadcastService.GROUP.isEmpty()) {
                LotteryBean lotteryBean = randomUser();
                if (lotteryBean == null)
                    break;
                progress.setData(lotteryBean);
                progress.setTime(System.currentTimeMillis());
                createResponse.setUserActionBean(progress);
                try {
                    BroadcastService.getInstance().broadcast(createResponse);
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            } else {
                LotteryServiceImpl.LOTTERY_USERS.clear();
                break;
            }
        }
        //luck
        if (!BroadcastService.GROUP.isEmpty()) {
            LotteryBean luckUser = randomUser();
            if (luckUser != null) {
                luckOper.setData(luckUser);
                luckOper.setTime(System.currentTimeMillis());
                try {
                    BroadcastService.getInstance().broadcast(createResponse.setUserActionBeanWithActionCode(luckOper, ActionCode.LOTTORY_LUCKLY));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        LotteryService.IS_START_LOTTERY.set(false);
        luckOper = null;
    }

    public static void setUserActionBean(UserActionBean ua) {
        if (luckOper == null) {
            luckOper = ua;
        }
    }

    private static UserActionBean luckOper = null;


    private LotteryBean randomUser() {

        LotteryBean luck = null;
        int index = random.nextInt(LotteryService.LOTTERY_USERS.size());
        int pos = 0;
        for (String s : LotteryService.LOTTERY_USERS.keySet()) {
            if (pos == index) {
                luck = LotteryService.LOTTERY_USERS.get(s);
                break;
            }
            pos++;
        }
        return luck;
    }
}
